/*
 *
 *  *    Copyright 2020-2021 Luter.me
 *  *
 *  *    Licensed under the Apache License, Version 2.0 (the "License");
 *  *    you may not use this file except in compliance with the License.
 *  *    You may obtain a copy of the License at
 *  *
 *  *      http://www.apache.org/licenses/LICENSE-2.0
 *  *
 *  *    Unless required by applicable law or agreed to in writing, software
 *  *    distributed under the License is distributed on an "AS IS" BASIS,
 *  *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  *    See the License for the specific language governing permissions and
 *  *    limitations under the License.
 *
 */

package com.luter.heimdall.plugins.thymeleaf.processor.element;

import com.luter.heimdall.plugins.thymeleaf.processor.AttrNameConstants;
import org.thymeleaf.context.ITemplateContext;
import org.thymeleaf.model.IProcessableElementTag;
import org.thymeleaf.processor.element.AbstractElementTagProcessor;
import org.thymeleaf.processor.element.IElementTagStructureHandler;
import org.thymeleaf.templatemode.TemplateMode;

import java.util.function.Predicate;

import static com.luter.heimdall.plugins.thymeleaf.util.ThymeleafFacade.getRawValue;

/**
 * 具备多个权限其中之一
 *
 * @author luter
 */
public class HasAnyPermsElementProcessor extends AbstractElementTagProcessor {
    /**
     * The constant DELIMITER.
     */
    private static final String DELIMITER = ",";
    /**
     * The constant ELEMENT_NAME.
     */
    private static final String ELEMENT_NAME = AttrNameConstants.HasAnyPerms.ELEMENT;
    /**
     * The constant PRECEDENCE.
     */
    private static final int PRECEDENCE = 300;
    private Predicate<String[]> condition;

    public HasAnyPermsElementProcessor condition(Predicate<String[]> condition) {
        this.condition = condition;
        return this;
    }
    /**
     * 具备多个权限其中之一
     *
     * @param dialectPrefix the dialect prefix
     */
    public HasAnyPermsElementProcessor(String dialectPrefix) {
        super(
                TemplateMode.HTML,
                dialectPrefix,
                ELEMENT_NAME,
                true,
                null,
                false,
                PRECEDENCE);
    }

    @Override
    protected void doProcess(ITemplateContext iTemplateContext,
                             IProcessableElementTag iProcessableElementTag,
                             IElementTagStructureHandler iElementTagStructureHandler) {
        String rawValue = getRawValue(iProcessableElementTag, "name");
        final String[] values = rawValue.split(DELIMITER);
        if (condition.test(values)) {
            iElementTagStructureHandler.removeTags();
        } else {
            iElementTagStructureHandler.removeElement();
        }
    }
}